package se.vgregion.excel.tools;

import java.io.InputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;

/**
 * 
 * Provide functionality that reads the conten from a zip-stream. I does nothing with the data it consumes. The
 * actual processing of this can be implemented by overwriting the visit method.
 * 
 * @author claes.lundahl
 */
public class ZipEntryVisitor {

    /**
     * Starts the reading that consumes the content in the provided input stream.
     * 
     * @param in
     *            stream to be read.
     */
    public void process(InputStream in) {
        try {

            byte[] readBuffer = new byte[2156];
            int bytesIn = 0;

            ZipInputStream zis = new ZipInputStream(in);
            ZipEntry entry;
            // while there are entries I process them
            while ((entry = zis.getNextEntry()) != null) {
                // consume all the data from this entry
                while (zis.available() > 0) {
                    bytesIn = zis.read(readBuffer);
                    if (bytesIn < 0) {
                        // nothing
                    } else {

                        visit(entry, bytesIn, readBuffer);

                        // I could close the entry, but getNextEntry does it automatically
                        // zis.closeEntry()
                    }
                }
            }

        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * Override this method to actually do something. This method is invoked during the reading of the stream and
     * gets called with byte chunks of the incomming zip-stream.
     * 
     * @param entry
     *            current entry that are beeing processed.
     * @param bytesIn
     *            the number of bytes that are part of this iteration.
     * @param readBuffer
     *            actual byte content of this chunk who have been read.
     */
    protected void visit(ZipEntry entry, int bytesIn, byte[] readBuffer) {

    }

}
